package com.ebt.m.customer.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.Fragment;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.customer.model.CustomerModel;
import com.ebt.m.customer.view.AvatarView;

import java.util.HashMap;
import java.util.List;

@SuppressLint("NewApi") 
public class AdapterCustomerChoose extends BaseAdapter {

	private static final String TAG = "wang";

	private static final float ROTATION_ANIM = -135f;
	private Context context;
	private List<CustomerModel> customerModels;
	private LayoutInflater inflater;
	
	private LruCache<String, Bitmap> mBitmapCache;
	private int MAXMEMONRY = 0;
	
	private MarginLayoutParams avatarParam;
	
	private HashMap<Integer, Integer> sectionToPosition = new HashMap();
	
	public AdapterCustomerChoose(Context context, List<CustomerModel> customerModels){
		this.context = context;
		this.customerModels = customerModels;
		this.inflater = LayoutInflater.from(context);
	
		if(MAXMEMONRY == 0){
			MAXMEMONRY = (int) (Runtime.getRuntime().maxMemory());
		}
		
		if (mBitmapCache == null){
			mBitmapCache = new LruCache<String, Bitmap>( MAXMEMONRY / 8) {
				
				@Override
				protected int sizeOf(String key, Bitmap bitmap) {
					return bitmap.getByteCount();
				}

				@Override
				protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
					if (evicted && oldValue !=null && !oldValue.isRecycled()) { 
						oldValue.recycle(); 
						oldValue = null; 
					}
				}
			};
		}
		
		if(sectionToPosition != null){
			sectionToPosition.clear();
		}
	}
	
	@Override
	public int getCount() {
		return customerModels.size();
	}

	@Override
	public Object getItem(int position) {
		return customerModels.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	private Fragment mFragment;
	
	public void setFragmentContainer(Fragment fragment){
		mFragment = fragment;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		CustomerModel item = (CustomerModel) getItem(position);
		
		ViewHolder viewHolder = null;
        if (null == convertView){
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.view_customer_item_choose, parent, false);
            viewHolder.tv_sort_key = (TextView) convertView.findViewById(R.id.tv_sort_key);
            viewHolder.iv_avatar = (AvatarView) convertView.findViewById(R.id.iv_avatar);
            viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        
        int section = getSectionForPosition(position);
		if (position == getPositionForSection(section)) {
			viewHolder.tv_sort_key.setText(String.valueOf(item.sortKeyChar));
			if(viewHolder.tv_sort_key.getVisibility() != View.VISIBLE){
				viewHolder.tv_sort_key.setVisibility(View.VISIBLE);
			}
		} else {
			if(viewHolder.tv_sort_key.getVisibility() != View.GONE){
				viewHolder.tv_sort_key.setVisibility(View.GONE);
			}
		}
		
        viewHolder.iv_avatar.setTag(item);
//        refreshAvatarImageView(viewHolder.iv_avatar, item);
//        new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, viewHolder.iv_avatar);
        viewHolder.tv_name.setText(item.name);
        AvatarView.updateAvatarView(viewHolder.iv_avatar, mBitmapCache, item.getCustomerUuid(), item.portraitPath, item.name);
        /*final AvatarView av = viewHolder.iv_avatar;
        Observable
                .create(new Observable.OnSubscribe<Bitmap>() {
                    @Override
                    public void call(Subscriber<? super Bitmap> subscriber) {
                        subscriber.onNext(getAvatarBitmapForAv(item));
                        subscriber.onCompleted();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Bitmap>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Bitmap b) {
                        if (((CustomerModel) av.getTag()).getCustomerUuid().equals(item.getCustomerUuid())) {
                            if (b == null) {
                                if (item.name == null || TextUtils.isEmpty(item.name.trim())) {
                                    av.setTextAndColorSeed(" ", " ");
                                } else {
                                    av.setTextAndColorSeed(item.name.trim().substring(0, 1), item.name);
                                }
                            } else {
                                av.setBitmap(b);
                            }
                        }
                    }
                });
        */
        return convertView;
	}

    private synchronized Bitmap getAvatarBitmapForAv(CustomerModel item){
        if (TextUtils.isEmpty(item.portraitPath)) {
            return null;
        }else{
            return getAvatarBitmap(item);
        }
    }

    private synchronized Bitmap getAvatarBitmap(CustomerModel item){
        Bitmap retBitmap = null;
        if(mBitmapCache != null) {
            retBitmap = mBitmapCache.get(item.getCustomerUuid());
        }
        if(retBitmap == null){
            retBitmap = BitmapFactory.decodeFile(item.portraitPath);
            if(retBitmap != null && mBitmapCache != null) {
                mBitmapCache.put(item.getCustomerUuid(), retBitmap);
            }
        }
        return retBitmap;
    }

   /* @SuppressLint("NewApi")
    private void refreshAvatarImageView(AvatarView av, CustomerModel item){
        if(av == null){
            return;
        }
        av.setTag(item);

        new AvatarAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, av);
    }*/

   /* class AvatarAsyncTask extends AsyncTask<AvatarView, Void, Object>{

        private AvatarView av;
        private CustomerModel item;
        @Override
        protected Object doInBackground(AvatarView... params) {
            av = params[0];
            item = (CustomerModel)(av.getTag());
            return getAvatarBitmap(item);
        }

        @Override
        protected void onPostExecute(Object result) {
            if(result == null){
                if(item.getCustomerUuid().equals(((CustomerModel) (av.getTag())).getCustomerUuid())){
                    av.setTextAndColorSeed(item.name.substring(0, 1), item.name);
                }
            }else{
                if(result instanceof Drawable){
                    if(item.getCustomerUuid().equals(((CustomerModel) (av.getTag())).getCustomerUuid())){
                        av.setDrawable((Drawable)result);
                    }
                }
            }
        }
    }*/

	private static class ViewHolder{
		public TextView tv_sort_key;
		public AvatarView iv_avatar;
		public TextView tv_name;
	}

	public int getSectionForPosition(int position) {
    	return customerModels.get(position).sortKeyChar;
    }

    public int getPositionForSection(int section) {
    	
    	Integer p = sectionToPosition.get(section);
    	if(p != null) {
    		return p;
    	}
		int size = customerModels.size();
		for (int i = 0; i < size; i++) {
			if (customerModels.get(i).sortKeyChar == section) {
				sectionToPosition.put(section, i);
				return i;
			}
		}
		return -1;
	}
    
    public void clearSectionToPositionCache(){
    	if(sectionToPosition != null){
			sectionToPosition.clear();
		}
    }
	
	/*private synchronized Bitmap getAvatarBitmap(CustomerModel item){
		Bitmap retBitmap = mBitmapCache.get(item.uuid);
		if(retBitmap != null){
			return retBitmap;
		}
		if (!TextUtils.isEmpty(item.portraitPath)) {
            retBitmap = BitmapFactory.decodeFile(item.portraitPath);
			if(retBitmap != null) {
                mBitmapCache.put(item.uuid, retBitmap);
            }
		}
		return retBitmap;
	}*/
	
}
